<?php

namespace app\order\controller;

use app\api\service\B2bRefundService;
use think\admin\Exception;
use think\facade\Request;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use app\order\model\ImsEweiShopOrder;
use app\goods\model\ImsEweiShopGoods;
use app\order\model\ImsEweiShopOrderGoods;
use EasyWeChat\MiniApp\Application;
use app\wechat\service\WechatService;
use app\wechat\model\WechatPaymentRecord;
use app\wechat\model\WechatFans;
use app\wechat\service\PaymentService;
use think\exception\HttpResponseException;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;


class Index extends Controller
{
    public function index()
    {
        $this->type = $this->get['type'] ?? '30';		
        ImsEweiShopOrder::mQuery()->layTable(function () {
            $this->title = '订单列表';
        }, function (QueryHelper $query) {
            $query->alias('o')->leftJoin('ims_ewei_shop_order_goods og ','og.orderid = o.id')->leftJoin('ims_ewei_shop_merch_user mu ','mu.id = o.merchid')->leftJoin('ims_ewei_shop_member sm ','sm.openid = o.openid')->leftJoin('ims_ewei_shop_goods g ','g.id = og.goodsid');
            
            $query->field("o.id,o.status,o.ordersn,o.address,o.openid,o.paytype,o.paytime,o.createtime,o.remark,o.transid,o.refund_amount,og.title,og.price,og.total,og.supplier_due,og.salesman_due,mu.merchname,sm.nickname,g.costprice,g.costnum");

            switch ($this->type) {
                case '1':
                    $query->where(' o.status=1 ');
                    break;
                case '2':
                    $query->where(' o.status=2 ');
                    break;
                case '3':
                    $query->where(' o.status=3 ');
                    break;
                case '-1':
                    $query->where(' o.status=-1 ');
                    break;				
                case '0':
                    $query->where(' o.status=0 ');
                    break;
				case '30':
                    $query->where(' o.status=30 ');
                    break;
                
                default:
                    $query->where(' o.status not in (0,1,2) ');
                    break;
            }
            $query->where(' og.id>0 ');

            // 数据列表搜索过滤
            $query->like('o.ordersn|o.openid|og.title|o.address#keywords');
			//echo ImsEweiShopOrder::mk()->getLastSql();
        });
        $this->fetch();
    }

    ### 当一个控制器存在多个page操作时，可以指定回调前缀
    protected function _index_page_filter(&$data){
      // 精准回调对 $data 进行二次处理，注意是引用
        foreach ($data as $k => $v) {
            $data[$k]['address'] = unserialize($v['address']);
            $data[$k]['addressstr'] = unserialize($v['address'])['province'].unserialize($v['address'])['city'].unserialize($v['address'])['area'].unserialize($v['address'])['address'];
            $data[$k]['paytypename'] = ImsEweiShopOrder::orderPaytypeStr($v['status'],$v['paytype']);
            $data[$k]['goodsname'] = $v['title'];
            $data[$k]['paytime'] = $v['paytime']>0 ? date('Y-m-d H:i:s',$v['paytime']) : 0;
            $data[$k]['ocostprice'] = $v['supplier_due']/$v['total']/$v['costnum'];

            if ($v['status'] == 2 && time()-$v['paytime'] > 86400*3) {
                ImsEweiShopOrder::checkStatus($v['id'],3);
            }elseif ( $v['transid']>0 ) {
                $record = WechatPaymentRecord::mk()->where('payment_trade','=',$v['transid'])->find()->toArray();
                if ($record['refund_status'] == 1 && $record['refund_amount'] == $v['price']) {
                    ImsEweiShopOrder::checkStatus($v['id'],-1);
                }
            }
        }

    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {

            $orderid = $this->get['id'] ?? '0';
            $goodsList = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$orderid])->select();
            foreach ($goodsList as $k => $v) {
                $goodsList[$k]['goodsinfo'] = ImsEweiShopGoods::mk()->where(['id'=>$v['goodsid']])->find()?ImsEweiShopGoods::mk()->where(['id'=>$v['goodsid']])->find()->toArray():[];
            }
            $this->orderGoodList = $goodsList;
            $vo['address'] = unserialize($vo['address']);
        }elseif ($this->request->isPost()) {

            $orderid = Request::param('id');
            $refund = Request::param('refund');
            $refund_amount = Request::param('refund_amount');
            $refund_reason = Request::param('refund_reason');

            if ($refund == 1) {
                //退款
                $orderinfo = ImsEweiShopOrder::mk()->where(['id'=>$orderid])->findOrEmpty();
                if ($orderinfo->isEmpty()) $this->error('订单不存在！');
                $recordinfo = WechatPaymentRecord::mk()->where('payment_trade','=',$orderinfo['transid'])->findOrEmpty();
                if ($recordinfo->isEmpty()) $this->error('支付单不存在！');
                if ($orderinfo['price'] - $orderinfo['refund_amount'] < $refund_amount) {
                    $this->error('退款金额超限！');
                }
                try {
                    $data = ['code'=>$recordinfo['code']];
                    $recode = WechatPaymentRecord::mk()->where($data)->findOrEmpty();
                    if ($recode->isEmpty()) $this->error('支付单不存在！');
                    if ($recode->getAttr('payment_status') < 1) $this->error('支付单未完成支付！');
                    $reason = "来自订单 {$recode['order_code']} 的退款！".$refund_reason;
                    sysoplog('微信支付退款', "支付单 {$data['code']} 发起退款！");
                    [$state, $message] = PaymentService::refund($data['code'], strval($refund_amount), $reason);
                    $state ? ImsEweiShopOrder::mk()->where(['id'=>$orderid])->update(['refund_amount'=>$refund_amount+$orderinfo['refund_amount']]) : "";
                    $state ? $this->success($message) : $this->error($message);
                } catch (HttpResponseException $exception) {
                    throw $exception;
                } catch (\Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
            /**
             * b2b退款流程
             */
            if ($refund == 2) {

                $orderinfo = ImsEweiShopOrder::mk()->where(['id'=>$orderid])->findOrEmpty();
                if ($orderinfo->isEmpty()){

                    $this->error('订单不存在！');
                }
                $recordinfo = WechatPaymentRecord::mk()->where('payment_trade','=',$orderinfo['transid'])->findOrEmpty();
                if ($recordinfo->isEmpty())
                {
                    $this->error('支付单不存在！');
                }
                if ($orderinfo['price'] - $orderinfo['refund_amount'] < $refund_amount)
                {
                    $this->error('退款金额超限！');
                }

                $data = ['code'=>$recordinfo['code']];
                $recode = WechatPaymentRecord::mk()->where($data)->findOrEmpty();
                if ($recode->isEmpty()){
                    $this->error('支付单不存在！');
                }
                if ($recode->getAttr('payment_status') < 1)
                {
                    $this->error('支付单未完成支付！');
                }
                $reason = "来自订单 {$recode['order_code']} 的退款！".$refund_reason;
                /**
                 * 处理退款请求
                 */
                try {
                    $b2bRefundService = new B2bRefundService();
                    [$state, $message]=$b2bRefundService->refund($data['code'], strval($refund_amount), $reason);
                    $state ? ImsEweiShopOrder::mk()->where(['id' => $orderid])->update(['refund_amount' => $refund_amount + $orderinfo['refund_amount']]) : "";
                    $state ? $this->success($message) : $this->error($message);

                } catch (InvalidResponseException $e) {
                    $this->error($e->getMessage());
                } catch (LocalCacheException $e) {
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

            }

        }
    }

    public function add()
    {
    }

    public function record()
    {
        ImsEweiShopOrder::mForm('record');
    }

    public function orderinfo()
    {
        ImsEweiShopOrder::mForm('info');
    }

    /**
     * 修改状态
     * @auth true
     */
    public function status()
    {
        $this->status = Request::param('status');
        $this->paytype = Request::param('paytype');
        $this->paytime = Request::param('paytime');
        if ($this->status == 1) {
            ImsEweiShopOrder::mSave($this->_vali([
                'status.in:1'  => '状态值范围异常！',
                'status.require' => '状态值不能为空！',
                'paytype.require' => '支付类型不能为空！',
                'paytime.require' => '状态值不能为空！',
            ]));
        }elseif($this->status == 2){
            //发货
            $res = ImsEweiShopOrder::wechatSend(Request::param('id'));
            ImsEweiShopOrder::mSave($this->_vali([
                'status.in:-1,0,1,2'  => '状态值范围异常！',
                'status.require' => '状态值不能为空！',
            ]));

        }else{
            ImsEweiShopOrder::mSave($this->_vali([
                'status.in:-1,0,1,2'  => '状态值范围异常！',
                'status.require' => '状态值不能为空！',
            ]));
        }
        
    }
    
}
